﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Windows.Forms;
using System.Data.Objects;
using ThaiHoa.Win.QLSX.Entity;
using ThaiHoa.Win.QLSX.Kho.UTI;
using ThaiHoa.Win.QLSX.DAL;
using Excel = Microsoft.Office.Interop.Excel;

namespace ThaiHoa.Win.QLSX.Kho.UI
{
    public partial class frmThepTamDetail_old : Form
    {
        #region Fields
        KhoDBContext db;
        BindingSource ThepTamBS;
        BindingSource macVatTuBS;
        private bool HasChanged = false;
        #endregion
        #region Contructor
        public frmThepTamDetail_old()
        {
            InitializeComponent();
        }
        #endregion
        #region Functions
        private void BindData()
        {
            db = new KhoDBContext();
            ThepTamBS = new BindingSource();
            this.ThepTamBS.AddingNew += new AddingNewEventHandler(ThepTamBS_AddingNew);
            this.ThepTamBS.ListChanged += new ListChangedEventHandler(ThepTamBS_ListChanged);
            db.ThepTam.Where(t => t.TrangThai).Include("LoaiVatTu").Load();
            ThepTamBS.DataSource = db.ThepTam.Local.ToBindingList();
            macVatTuBS = new BindingSource();
            db.MacVatTu.Where(m => m.TrangThai).Load();
            macVatTuBS.DataSource = db.MacVatTu.Local.ToBindingList();
            //binding for navigator
            thepTamBN.BindingSource = ThepTamBS;
            //binding for gridview
            dgvThepTam.AutoGenerateColumns = true;
            dgvThepTam.DataSource = ThepTamBS;
            CustomerGridView();
            //binding for textbox
            txtMa.DataBindings.Add("Text", ThepTamBS, "MaMatHang");
            txtTen.DataBindings.Add("Text", ThepTamBS, "TenMatHang");
            txtChieuDay.DataBindings.Add("Text", ThepTamBS, "ChieuDay");
            txtKichThuocDai.DataBindings.Add("Text", ThepTamBS, "KichThuocDai");
            txtChieuDaiDai.DataBindings.Add("Text", ThepTamBS, "ChieuDaiDai");
            txtDaiPerTam.DataBindings.Add("Text", ThepTamBS, "SoLuongDaiPerTam");
            txtChiTietPerDai.DataBindings.Add("Text", ThepTamBS, "SoLuongChiTietPerDai");
            txtChiTietPerTam.DataBindings.Add("Text", ThepTamBS, "SoLuongChiTietPerTam");
            txtTrongLuongTam.DataBindings.Add("Text", ThepTamBS, "TrongLuongTam");
            txtTLPhoiPerCT.DataBindings.Add("Text", ThepTamBS, "TiLePhoiPerChiTiet");
            txtTiLeNG.DataBindings.Add("Text", ThepTamBS, "TyLeNG");
            //binding for combobox
            cbMacThep.DataBindings.Add("SelectedItem", ThepTamBS, "MacThep", true);
            cbMacThep.DataSource = macVatTuBS;
        }
        private void CustomerGridView()
        {
            //Ẩn toàn bộ columns
            foreach (DataGridViewColumn item in dgvThepTam.Columns)
            {
                item.Visible = false;
            }
            //Tùy chỉnh lại
            //Mã
            var c = dgvThepTam.Columns["MaMatHang"];
            c.Visible = true;
            c.Width = 200;
            c.DisplayIndex = 1;

            //Tên
            c = dgvThepTam.Columns["TenMatHang"];
            c.Visible = true;
            c.Width = 200;
            c.DisplayIndex = 2;

            //mác thép
            c = dgvThepTam.Columns["MacThep"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 3;
            c.ReadOnly = true;

            //Chiều dày
            c = dgvThepTam.Columns["ChieuDay"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 4;

            //Kích thước dải
            c = dgvThepTam.Columns["KichThuocDai"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 5;

            //Chiều dài dải
            c = dgvThepTam.Columns["ChieuDaiDai"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 6;

            //Số lượng dải / tấm
            c = dgvThepTam.Columns["SoLuongDaiPerTam"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 7;

            //Số chi tiết / dải
            c = dgvThepTam.Columns["SoChiTietPerDai"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 8;

            //Số lượng chi tiết / tấm
            c = dgvThepTam.Columns["SoLuongChiTietPerTam"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 9;

            //Trọng lượng tấm
            c = dgvThepTam.Columns["TrongLuongTam"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 10;

            //TL Phôi / CT
            c = dgvThepTam.Columns["TiLePhoiPerChiTiet"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 11;



            //Tỷ lệ NG
            c = dgvThepTam.Columns["TyLeNG"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 12;
        }
        private void SaveChange()
        {
            if (HasChanged)
            {
                if (MessageBox.Show("Lưu thay đổi ?", "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    db.SaveChanges();
                    HasChanged = false;
                }
            }
        }

        /// <summary>
        /// Kiểm tra có trùng mã ko
        /// Dung cho truong hop them moi
        /// True : Ko trùng
        /// False :Trùng
        /// </summary>
        /// <param name="maMatHang"></param>
        /// <returns></returns>
        private bool KiemTraTrungMa(string maMatHang)
        {
            List<MatHang> listMatHang = db.MatHang.Where(m => m.TrangThai).ToList();
            if (listMatHang.Any(l => l.MaMatHang.Equals(maMatHang)))
                return false;
            return true;
        }
        /// <summary>
        /// Kiem tra co trung ma ko
        /// Dung cho truong hop edit
        /// 
        /// </summary>
        /// <param name="maMatHang"></param>
        /// <param name="ThepTam"></param>
        /// <returns></returns>
        private bool KiemTraTrungMa(string maMatHang, ThepTam ThepTam)
        {
            List<MatHang> listMatHang = db.MatHang.Where(m => m.TrangThai).ToList();
            if (listMatHang.Any(l => !l.Equals(ThepTam) && l.MaMatHang.Equals(maMatHang)))
                return false;
            return true;
        }
        private void ExportToExcel()
        {
            string workbookPath =Application.StartupPath+ @"\Template\Excel\JAT_VatTu_DanhMucThepTam";
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(workbookPath,
                0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[1];
            xlWorkBook.Activate();
            xlWorkSheet.Name = "ThepTam";
            //Add data
            var listThepTam = ThepTamBS.List;
            int count = 0;
            int positionStart = 6;
            Excel.Range r;
            foreach (ThepTam item in listThepTam)
            {
                xlWorkSheet.Cells[positionStart + count, 1] = count + 1;
                xlWorkSheet.Cells[positionStart + count, 2] = item.MaMatHang;
                xlWorkSheet.Cells[positionStart + count, 3] = item.TenMatHang;
                xlWorkSheet.Cells[positionStart + count, 4] = item.MacThep.Tenmac;
                xlWorkSheet.Cells[positionStart + count, 5] = item.ChieuDay;
                xlWorkSheet.Cells[positionStart + count, 6] = item.KichThuocDai;
                xlWorkSheet.Cells[positionStart + count, 7] = item.ChieuDaiDai;
                xlWorkSheet.Cells[positionStart + count, 8] = item.SoLuongDaiPerTam;
                xlWorkSheet.Cells[positionStart + count, 9] = item.SoLuongChiTietPerDai;
                xlWorkSheet.Cells[positionStart + count, 10] = item.SoLuongChiTietPerTam;
                xlWorkSheet.Cells[positionStart + count, 11] = item.TrongLuongTam;
                xlWorkSheet.Cells[positionStart + count, 12] = item.TiLePhoiPerChiTiet;
                xlWorkSheet.Cells[positionStart + count, 13] = item.TyLeNG;

                //Format it               

                string start = "A" + (count + positionStart).ToString();
                string stop = "M" + (count + positionStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                r.Borders.Color = Color.Black;
                r.RowHeight = 30;
                //r.Style.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                r.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                count++;

            }
            // Ẩn chương trình
            xlApp.Visible = false;

            // Save file
            xlWorkBook.SaveAs("C:\\JAT_VatTu_DanhMucThepTam_1.xls", Excel.XlFileFormat.xlWorkbookNormal,
                            null, null, false, false,
                            Excel.XlSaveAsAccessMode.xlExclusive,
                            false, false, false, false, false);
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);



            MessageBox.Show("File created !");
        }
        #endregion
        #region Events
        private void frmThepTamDetail_Load(object sender, EventArgs e)
        {

            BindData();
            HasChanged = false;
        }
        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            SaveChange();
        }
        private void dgvThepTam_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            Common.ShowMessengerError(e.Exception.Message);
        }

        private void dgvThepTam_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

            // Bắt lỗi cho cell MaMatHang

            if (dgvThepTam.Columns[e.ColumnIndex].Name == "MaMatHang")
            {
                if (this.dgvThepTam.IsCurrentCellInEditMode)
                {
                    Guid oldId = (Guid)dgvThepTam.CurrentRow.Cells["Id"].Value;
                    if (oldId == null) return;
                    ThepTam oldThepTam = db.ThepTam.FirstOrDefault(t => t.Id.Equals(oldId));
                    if (oldThepTam == null) return;
                    if (!KiemTraTrungMa(e.FormattedValue.ToString(), oldThepTam))
                    {
                        Common.ShowMessengerError("Mã này đã được sử dụng");
                        this.dgvThepTam.EditingControl.Text = oldThepTam.MaMatHang;
                        e.Cancel = true;
                    }
                }
            }

        }

        private void dgvThepTam_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            var value = dgvThepTam.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

            //Bắt lỗi cho cell TyLeNG
            if (dgvThepTam.Columns[e.ColumnIndex].DataPropertyName == "TyLeNG")
            {
                double tryDouble;
                if (Double.TryParse(value.ToString(), out tryDouble))
                {
                    if (tryDouble < 0 || tryDouble > 100)
                    {
                        Common.ShowMessengerError("TyLeNG is not valid! " + tryDouble.ToString());
                        dgvThepTam.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                    }
                }
                else
                {
                    Common.ShowMessengerError("TyLeNG is not valid!");
                    dgvThepTam.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                }
            }

        }


        private void ThepTamBS_AddingNew(object sender, AddingNewEventArgs e)
        {

            ThepTam ThepTam = new ThepTam();
            LoaiVatTu loaiVatTu = db.LoaiVatTu.FirstOrDefault(l => l.TenLoai.Equals("Thép Tấm"));
            if (loaiVatTu == null)
            {
                loaiVatTu = new LoaiVatTu();
                loaiVatTu.TenLoai = "Thép Tấm";

            }
            MacVatTu macVatTu = db.MacVatTu.FirstOrDefault(m => m.LoaiVatTu.TenLoai.Equals("Thép Tấm"));
            if (macVatTu == null)
            {
                macVatTu = new MacVatTu();
                macVatTu.LoaiVatTu = loaiVatTu;
                macVatTu.Tenmac = "SH100";
            }
            ThepTam.LoaiVatTu = loaiVatTu;
            ThepTam.MacThep = macVatTu;
            e.NewObject = ThepTam;

        }
        private void ThepTamBS_ListChanged(object sender, ListChangedEventArgs e)
        {
            HasChanged = true;
        }
        private void printToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private void exportToolTripButton_Click(object sender, EventArgs e)
        {
            ExportToExcel();
        }
        private void frmThepTamDetail_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveChange();
        }
        #endregion

        

    }
}
